package com.guoyh.baseutils.ext

import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.EditText
import com.guoyh.bilbase.ext.textString

/**
 * @CreateDate: 2021/8/24 4:53 下午
 * @Author: guoyh
 * @Description: java类作用描述
 */

/**
 * 优化输入框 只抽取afterTextChanged方法
 */
fun EditText.afterTextChange(afterTextChanged: (String) -> Unit) {

    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            afterTextChanged.invoke(s.toString())
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }
    })
}

/**
 * 多个 Edittext 同一个监听
 */
fun afterTextChanges(vararg editText: EditText, afterTextChanged: (String, View) -> Unit) {
    editText.forEach {
        it.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                afterTextChanged.invoke(s.toString(),it)
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })
    }
}


fun EditText.showPwd(isChecked: Boolean) {
    inputType = if (isChecked) {
        InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
    } else {
        InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
    }
    setSelection(textString().length)
}



fun EditText.setTexts(msg: String) {
    setText(msg)
    if (!msg.isNullOrEmpty()) {
        setSelection(msg.length)
    }
}



fun EditText.setNullStr() {
    setText("")
}

/**
 * 获取文本
 */
fun EditText.textString(): String {
    return this.text.toString()
}

/**
 * 获取去除空字符串的文本
 */
fun EditText.textStringTrim(): String {
    return this.textString().trim()
}


/**
 * 可以正常输入
 */
fun EditText.canInput(isCan: Boolean) {
    isEnabled = isCan
}


/**
 * 文本是否为空
 */
fun EditText.isEmpty(): Boolean {
    return this.textString().isEmpty()
}

/**
 * 去空字符串后文本是否为空
 */
fun EditText.isTrimEmpty(): Boolean {
    return this.textStringTrim().isEmpty()
}


fun EditText.seePw(isSee:Boolean){
    this.transformationMethod =
        if (isSee) {
            HideReturnsTransformationMethod.getInstance();
        } else {
            PasswordTransformationMethod.getInstance();
        }
    setSelection(textString().length)
}